package wong.board.client.util;

import java.util.Iterator;
import java.util.NoSuchElementException;

import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONValue;

public class IterableJSONArray<V extends JSONValue> implements Iterable<V>, Iterator<V> {
	private JSONArray delegate;
	private int index = -1;

	// private boolean alreadyRemoved = false;

	public IterableJSONArray(JSONArray delegate) {
		this.delegate = delegate;
	}

	@Override
	public Iterator<V> iterator() {
		return this;
	}

	@Override
	public boolean hasNext() {
		return (this.delegate != null && ((this.index + 1) < this.delegate.size()));
	}

	@SuppressWarnings("unchecked")
	@Override
	public V next() {
		if (!hasNext()) {
			throw new NoSuchElementException("no more elements");
		}
		// alreadyRemoved = false;
		V value = (V) this.delegate.get(index++);
		if (index >= this.delegate.size()) {
			this.delegate = null;
		}
		return value;
	}

	@Override
	public void remove() {
		throw new UnsupportedOperationException("remove() is not supported");
	}

}